<template>
  <el-dialog
    :title="title"
    v-model="visible"
    width="900px"
    :close-on-click-modal="false"
    @closed="$emit('close')"
  >
    <el-form :model="form" label-width="120px">
      <el-form-item label="分组名" prop="groupName" required
        :rules="[{ required: true, message: '分组名不能为空', trigger: 'blur' }]">
        <el-input v-model="form.groupName" placeholder="请输入分组名" />
      </el-form-item>
      
      <el-form-item label="可查看单位">
        <div style="display: flex; align-items: center; gap: 10px;">
          <el-select
            v-model="form.viewableUnits"
            multiple
            filterable
            placeholder="请选择可查看单位"
            style="flex: 1;"
          >
            <el-option
              v-for="item in unitOptions"
              :key="item.value"
              :label="`${item.label} (${item.code})`"
              :value="item.value"
            />
          </el-select>
          <el-button @click="selectAllUnits" size="small" type="primary">全选</el-button>
        </div>
      </el-form-item>
      
      <el-form-item label="可查看表">
        <el-table
          :data="form.viewableTables"
          border
          style="width: 100%; margin-bottom: 10px;"
        >
          <el-table-column
            label="表名"
            prop="name"
            width="180"
          >
            <template #default="{row}">
              <el-select
                v-model="row.key"
                placeholder="请选择表名"
                filterable
                @change="(val) => handleTableChange(row, val)"
              >
                <el-option
                  v-for="item in tableOptions"
                  :key="item.key"
                  :label="item.label"
                  :value="item.key"
                  :disabled="isTableSelected(item.key, row)"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            label="列名"
            prop="columns"
         
          >
            <template #default="{row}">
              <div style="display: flex; align-items: center; gap: 10px;">
                <el-select
                  v-model="row.selectedColumns"
                  multiple
                  filterable
                  placeholder="请选择列名"
                  style="flex: 1;"
                >
                  <el-option
                    v-for="column in row.columns"
                    :key="column.fieldName"
                    :label="column.comment"
                    :value="column.fieldName"
                  />
                </el-select>
                <el-button @click="selectAndDeselectAllColumns(row, true)" size="small" type="primary">全选</el-button>
                <el-button @click="selectAndDeselectAllColumns(row, false)" size="small" type="info">取消</el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="80"
            align="center"
          >
            <template #default="{row}">
              <el-button
                size="mini"
                type="danger"
                @click="handleDeleteRow(row)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          @click="handleAddRow"
          size="mini"
        >
          <el-icon><Plus /></el-icon> 新增行
        </el-button>
      </el-form-item>
    </el-form>
        
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import database from '../../../utils/database.js'

const props = defineProps({
  title: String,
  form: {
    type: Object,
    required: true,
    validator: (value) => {
      // 确保form对象存在且包含必要的属性
      if (!value) return false;
      if (!Array.isArray(value.viewableTables)) {
        value.viewableTables = [];
      }
      if (!Array.isArray(value.viewableUnits)) {
        value.viewableUnits = [];
      }
      return true;
    }
  },
  isEdit: Boolean
})

// 表列信息
const tableColumns = {
        'subUnits': [
          // { fieldName: 'id', comment: 'ID' },
          { fieldName: 'code', comment: '单位编码' },
          { fieldName: 'name', comment: '单位名称' },
          { fieldName: 'status', comment: '状态' },
          // { fieldName: 'created_at', comment: '创建时间' },
          // { fieldName: 'updated_at', comment: '更新时间' }
        ],
        'leader_personnel_infro': [
          // { fieldName: 'id', comment: 'ID' },
          { fieldName: 'personnel_code', comment: '人员编码' },
          { fieldName: 'unit_name', comment: '单位名称' },
          { fieldName: 'department_name', comment: '部门名称' },
          { fieldName: 'name', comment: '姓名' },
          { fieldName: 'gender', comment: '性别' },
          { fieldName: 'birth_date', comment: '出生日期' },
          { fieldName: 'nationality', comment: '民族' },
          { fieldName: 'native_place', comment: '籍贯' },
          { fieldName: 'birth_place', comment: '出生地' },
          { fieldName: 'work_start_date', comment: '参加工作日期' },
          { fieldName: 'health_status', comment: '健康状况' },
          { fieldName: 'appointment_title', comment: '聘任职称' },
          { fieldName: 'education_level', comment: '学历' },
          { fieldName: 'graduate_school', comment: '毕业学校' },
          { fieldName: 'major_studied', comment: '所学专业' },
          { fieldName: 'study_type', comment: '学习类型' },
          { fieldName: 'current_position', comment: '现任行政职务' },
          { fieldName: 'position_level', comment: '职务级别' },
          { fieldName: 'graduation_date', comment: '毕业日期' },
          { fieldName: 'political_status', comment: '政治面貌' },
          { fieldName: 'id_card_number', comment: '身份证号' },
          { fieldName: 'resume', comment: '个人履历' },
          // { fieldName: 'created_at', comment: '创建时间' },
          // { fieldName: 'updated_at', comment: '更新时间' },
          // { fieldName: 'created_by', comment: '创建人' },
          // { fieldName: 'updated_by', comment: '更新人' }
        ],
        'new_leader_report': [
          // { fieldName: 'id', comment: 'ID' },
          { fieldName: 'report_name', comment: '报告人姓名' },
          { fieldName: 'unit', comment: '单位' },
          { fieldName: 'position', comment: '职务' },
          { fieldName: 'gender', comment: '性别' },
          { fieldName: 'phone_number', comment: '手机号码' },
          { fieldName: 'id_number', comment: '身份证号' },
          { fieldName: 'political_status', comment: '政治面貌' },
          { fieldName: 'serious_illness', comment: '本人是否身患重大疾病' },
          { fieldName: 'marital_status', comment: '婚姻情况' },
          { fieldName: 'registered_address', comment: '户籍地具体地址' },
          { fieldName: 'passport_and_permits_info', comment: '本人取得普通护照、往来港澳通行证等情况' },
          { fieldName: 'overseas_social_media_info', comment: '本人因私设立使用国（境）外社交媒体账号情况' },
          { fieldName: 'children_international_marriage_info', comment: '子女与外国人、无国籍人、港澳台居民通婚的情况' },
          { fieldName: 'family_overseas_residency_info', comment: '配偶子女移居国（境）外等情况' },
          { fieldName: 'family_business_positions_info', comment: '配偶子女及其配偶受聘担任私营企业高级职务等情况' },
          { fieldName: 'legal_and_disciplinary_actions', comment: '本人配偶子女及其配偶被司法机关追究刑事责任等情况' },
          { fieldName: 'investigation_and_interrogation_info', comment: '本人涉嫌违规违纪违法犯罪问题等情况' },
          { fieldName: 'dishonest_person_status', comment: '本人或者配偶列为失信被执行人的情况' },
          { fieldName: 'relatives_basicInfro', comment: '亲属基本信息' },
          { fieldName: 'relatives_houseInfro', comment: '房产情况信息' },
          { fieldName: 'relatives_workin_railway', comment: '在铁路系统工作情况' },
          { fieldName: 'other_matters', comment: '其他需要报告的事项' },
          // { fieldName: 'created_at', comment: '创建时间' },
          // { fieldName: 'updated_at', comment: '更新时间' }
        ],
        'problem_clues_situation': [
          // { fieldName: 'id', comment: 'ID' },
          // 基本信息
          { fieldName: 'main_mark', comment: '主件标识' },
          { fieldName: 'is_unit', comment: '是否单位' },
          { fieldName: 'report_unit_name', comment: '填报单位名称' },
          { fieldName: 'report_unit_code', comment: '填报单位代码' },
          { fieldName: 'reflected_person', comment: '被反映人' },
          { fieldName: 'work_unit_and_position', comment: '工作单位及职务' },
          { fieldName: 'rank', comment: '职级' },
          { fieldName: 'handling_agency', comment: '办理机关' },
          { fieldName: 'main_problem_clue', comment: '主要问题线索' },
          { fieldName: 'petition_code', comment: '信访编码' },
          // 受理信息
          { fieldName: 'accept_clue_code', comment: '受理线索编码' },
          { fieldName: 'accept_person_code', comment: '受理人员编码' },
          { fieldName: 'disposal_clue_code', comment: '处置线索编码' },
          { fieldName: 'disposal_person_code', comment: '处置人员编码' },
          // 对象信息
          { fieldName: 'is_national_supervision_object', comment: '是否国家监察对象' },
          { fieldName: 'recover_economic_loss', comment: '挽回经济损失（万元）' },
          { fieldName: 'recovery_amount', comment: '收缴金额（万元）' },
          { fieldName: 'confiscation_amount', comment: '没收金额' },
          { fieldName: 'order_refund_amount', comment: '责令退赔金额' },
          { fieldName: 'register_submit_amount', comment: '登记上交金额' },
          { fieldName: 'recover_loss_due_to_misconduct', comment: '追缴失职渎职滥用职权造成的损失金额' },
          { fieldName: 'remarks', comment: '备注' },
          // 个人信息
          { fieldName: 'ethnicity', comment: '民族' },
          { fieldName: 'birth_date', comment: '出生年月' },
          { fieldName: 'npc_member', comment: '人大代表' },
          { fieldName: 'cppcc_member', comment: '政协委员' },
          { fieldName: 'is_discipline_inspection_official', comment: '是否纪检监察干部' },
          { fieldName: 'disposal_report', comment: '处置情况报告' },
          { fieldName: 'party_join_date', comment: '入党时间' },
          { fieldName: 'cadre_management_authority', comment: '干部管理权限' },
          { fieldName: 'central_managed_cadre_level2', comment: '中管干部二级' },
          // { fieldName: 'id_number', comment: '身份证号' },
          // 时间信息
          { fieldName: 'accept_time', comment: '受理时间' },
          { fieldName: 'accept_stat_time', comment: '受理统计时间' },
          // 处置方式（8种）
          { fieldName: 'disposal_method1_approval_time', comment: '处置方式1批准时间' },
          { fieldName: 'disposal_method1_stat_time', comment: '处置方式1统计时间' },
          { fieldName: 'disposal_method1_level1', comment: '处置方式1一级' },
          { fieldName: 'disposal_method1_level2', comment: '处置方式1二级' },
          { fieldName: 'disposal_method2_approval_time', comment: '处置方式2批准时间' },
          { fieldName: 'disposal_method2_stat_time', comment: '处置方式2统计时间' },
          { fieldName: 'disposal_method2_level1', comment: '处置方式2一级' },
          { fieldName: 'disposal_method2_level2', comment: '处置方式2二级' },
          { fieldName: 'disposal_method3_approval_time', comment: '处置方式3批准时间' },
          { fieldName: 'disposal_method3_stat_time', comment: '处置方式3统计时间' },
          { fieldName: 'disposal_method3_level1', comment: '处置方式3一级' },
          { fieldName: 'disposal_method3_level2', comment: '处置方式3二级' },
          { fieldName: 'disposal_method4_approval_time', comment: '处置方式4批准时间' },
          { fieldName: 'disposal_method4_stat_time', comment: '处置方式4统计时间' },
          { fieldName: 'disposal_method4_level1', comment: '处置方式4一级' },
          { fieldName: 'disposal_method4_level2', comment: '处置方式4二级' },
          { fieldName: 'disposal_method5_approval_time', comment: '处置方式5批准时间' },
          { fieldName: 'disposal_method5_stat_time', comment: '处置方式5统计时间' },
          { fieldName: 'disposal_method5_level1', comment: '处置方式5一级' },
          { fieldName: 'disposal_method5_level2', comment: '处置方式5二级' },
          { fieldName: 'disposal_method6_approval_time', comment: '处置方式6批准时间' },
          { fieldName: 'disposal_method6_stat_time', comment: '处置方式6统计时间' },
          { fieldName: 'disposal_method6_level1', comment: '处置方式6一级' },
          { fieldName: 'disposal_method6_level2', comment: '处置方式6二级' },
          { fieldName: 'disposal_method7_approval_time', comment: '处置方式7批准时间' },
          { fieldName: 'disposal_method7_stat_time', comment: '处置方式7统计时间' },
          { fieldName: 'disposal_method7_level1', comment: '处置方式7一级' },
          { fieldName: 'disposal_method7_level2', comment: '处置方式7二级' },
          { fieldName: 'disposal_method8_approval_time', comment: '处置方式8批准时间' },
          { fieldName: 'disposal_method8_stat_time', comment: '处置方式8统计时间' },
          { fieldName: 'disposal_method8_level1', comment: '处置方式8一级' },
          { fieldName: 'disposal_method8_level2', comment: '处置方式8二级' },
          // 线索来源
          { fieldName: 'clue_source', comment: '线索来源' },
          { fieldName: 'inspection_found_level2', comment: '巡视巡察中发现二级分类' },
          { fieldName: 'superior_assigned_level2', comment: '上级交办转办二级分类' },
          { fieldName: 'is_verified_with_person', comment: '是否与本人核实' },
          { fieldName: 'is_voluntary_confession', comment: '是否主动交代问题' },
          { fieldName: 'is_explained_in_meeting', comment: '是否在民主生活会上作说明' },
          // 办理结果
          { fieldName: 'handling_result', comment: '办理结果' },
          { fieldName: 'closing_time', comment: '办结时间' },
          { fieldName: 'closing_stat_time', comment: '办结统计时间' },
          // 身份分类
          { fieldName: 'is_party_member', comment: '是否党员' },
          { fieldName: 'supervision_object_level2', comment: '监察对象二级分类' },
          { fieldName: 'is_non_party_non_supervision', comment: '是否非党员非监察对象' },
          { fieldName: 'non_party_non_supervision_level2', comment: '非党员非监察对象二级分类' },
          // 行为分类
          { fieldName: 'disciplinary_violation', comment: '违纪行为' },
          { fieldName: 'duty_illegal_crime', comment: '职务违法犯罪行为' },
          { fieldName: 'other_illegal_crime', comment: '其他违法犯罪行为' },
          // 组织措施
          { fieldName: 'organizational_measures', comment: '组织措施' },
          { fieldName: 'organizational_measures_stat_time', comment: '组织措施统计时间' },
          { fieldName: 'is_voluntary_surrender', comment: '是否主动投案' },
          { fieldName: 'is_report_to_superior', comment: '是否属于向上级报告范围' },
          // 调查措施
          { fieldName: 'tech_investigation_measure_count', comment: '技术调查措施使用次数' },
          { fieldName: 'exit_restriction_measure_count', comment: '限制出境措施使用次数' },
          { fieldName: 'tech_investigation_doc_number', comment: '技术调查措施文书编号' },
          { fieldName: 'exit_restriction_doc_number', comment: '限制出境措施文书编号' },
          { fieldName: 'measure_stat_time', comment: '使用措施统计时间' },
          // 办理环节
          { fieldName: 'transfer_to_handling', comment: '转入办理环节' },
          { fieldName: 'transfer_department_name', comment: '移交其他部门办理-部门名称' },
          // 违纪违法行为时间
          { fieldName: 'violation_occurrence_time', comment: '违纪违法行为发生时间' },
          // 纪检监察建议（8条）
          { fieldName: 'suggesting_agency1', comment: '提出建议的纪检监察机构名称1' },
          { fieldName: 'suggested_unit1', comment: '被建议的单位（组织）名称1' },
          { fieldName: 'suggestion_type1', comment: '建议类型1' },
          { fieldName: 'suggestion_content1', comment: '建议文书内容1' },
          { fieldName: 'suggestion_time1', comment: '提出建议时间1' },
          { fieldName: 'suggestion_stat_time1', comment: '提出建议统计时间1' },
          { fieldName: 'suggesting_agency2', comment: '提出建议的纪检监察机构名称2' },
          { fieldName: 'suggested_unit2', comment: '被建议的单位（组织）名称2' },
          { fieldName: 'suggestion_type2', comment: '建议类型2' },
          { fieldName: 'suggestion_content2', comment: '建议文书内容2' },
          { fieldName: 'suggestion_time2', comment: '提出建议时间2' },
          { fieldName: 'suggestion_stat_time2', comment: '提出建议统计时间2' },
          { fieldName: 'suggesting_agency3', comment: '提出建议的纪检监察机构名称3' },
          { fieldName: 'suggested_unit3', comment: '被建议的单位（组织）名称3' },
          { fieldName: 'suggestion_type3', comment: '建议类型3' },
          { fieldName: 'suggestion_content3', comment: '建议文书内容3' },
          { fieldName: 'suggestion_time3', comment: '提出建议时间3' },
          { fieldName: 'suggestion_stat_time3', comment: '提出建议统计时间3' },
          { fieldName: 'suggesting_agency4', comment: '提出建议的纪检监察机构名称4' },
          { fieldName: 'suggested_unit4', comment: '被建议的单位（组织）名称4' },
          { fieldName: 'suggestion_type4', comment: '建议类型4' },
          { fieldName: 'suggestion_content4', comment: '建议文书内容4' },
          { fieldName: 'suggestion_time4', comment: '提出建议时间4' },
          { fieldName: 'suggestion_stat_time4', comment: '提出建议统计时间4' },
          { fieldName: 'suggesting_agency5', comment: '提出建议的纪检监察机构名称5' },
          { fieldName: 'suggested_unit5', comment: '被建议的单位（组织）名称5' },
          { fieldName: 'suggestion_type5', comment: '建议类型5' },
          { fieldName: 'suggestion_content5', comment: '建议文书内容5' },
          { fieldName: 'suggestion_time5', comment: '提出建议时间5' },
          { fieldName: 'suggestion_stat_time5', comment: '提出建议统计时间5' },
          { fieldName: 'suggesting_agency6', comment: '提出建议的纪检监察机构名称6' },
          { fieldName: 'suggested_unit6', comment: '被建议的单位（组织）名称6' },
          { fieldName: 'suggestion_type6', comment: '建议类型6' },
          { fieldName: 'suggestion_content6', comment: '建议文书内容6' },
          { fieldName: 'suggestion_time6', comment: '提出建议时间6' },
          { fieldName: 'suggestion_stat_time6', comment: '提出建议统计时间6' },
          { fieldName: 'suggesting_agency7', comment: '提出建议的纪检监察机构名称7' },
          { fieldName: 'suggested_unit7', comment: '被建议的单位（组织）名称7' },
          { fieldName: 'suggestion_type7', comment: '建议类型7' },
          { fieldName: 'suggestion_content7', comment: '建议文书内容7' },
          { fieldName: 'suggestion_time7', comment: '提出建议时间7' },
          { fieldName: 'suggestion_stat_time7', comment: '提出建议统计时间7' },
          { fieldName: 'suggesting_agency8', comment: '提出建议的纪检监察机构名称8' },
          { fieldName: 'suggested_unit8', comment: '被建议的单位（组织）名称8' },
          { fieldName: 'suggestion_type8', comment: '建议类型8' },
          { fieldName: 'suggestion_content8', comment: '建议文书内容8' },
          { fieldName: 'suggestion_time8', comment: '提出建议时间8' },
          { fieldName: 'suggestion_stat_time8', comment: '提出建议统计时间8' },
                    { fieldName: 'impact_end_date', comment: '影响期限结束时间' },

          // 时间统计
          { fieldName: 'handling_time', comment: '办理时间' },
          { fieldName: 'handling_stat_time', comment: '办理统计时间' },
          { fieldName: 'remarks_stat_time', comment: '备注统计时间' },
          // 涉外信息
          { fieldName: 'foreign_related_category', comment: '涉外类别' },
          { fieldName: 'involved_country', comment: '涉及国家（地区）' },
          { fieldName: 'foreign_related_stat_time', comment: '涉外统计时间' },
          { fieldName: 'foreign_related_summary', comment: '涉外信息摘要' },
          // 四种形态
          { fieldName: 'four_forms_situation', comment: '四种形态情形' },
          { fieldName: 'four_forms_stat_time', comment: '四种形态统计时间' },
          // 系统字段
          // { fieldName: 'created_at', comment: '创建时间' },
          // { fieldName: 'updated_at', comment: '更新时间' }
        ],
        'discipline_organization_punishment': [
          // { fieldName: 'id', comment: 'ID' },
          // 基本信息
          { fieldName: 'report_unit_name', comment: '填报单位名称' },
          { fieldName: 'report_unit_code', comment: '填报单位代码' },
          { fieldName: 'investigated_person', comment: '被调查人' },
          { fieldName: 'work_unit_and_position', comment: '工作单位及职务' },
          { fieldName: 'rank', comment: '职级' },
          { fieldName: 'cadre_management_authority', comment: '干部管理权限' },
          { fieldName: 'central_managed_cadre_level2', comment: '中管干部二级' },
          { fieldName: 'is_unit_or_accident', comment: '是否单位或事故' },
          // 案件信息
          { fieldName: 'case_code', comment: '案件编码' },
          { fieldName: 'involved_person_code', comment: '涉案人员编码' },
          // 个人信息
          { fieldName: 'id_type', comment: '证件类型' },
          { fieldName: 'id_number', comment: '证件号码' },
          { fieldName: 'gender', comment: '性别' },
          { fieldName: 'age', comment: '年龄' },
          { fieldName: 'birth_date', comment: '出生年月' },
          { fieldName: 'education', comment: '学历' },
          { fieldName: 'ethnicity', comment: '民族' },
          { fieldName: 'is_national_supervision_object', comment: '是否国家监察对象' },
          { fieldName: 'national_supervision_object_detail', comment: '国家监察对象详情' },
          { fieldName: 'is_ccp_member', comment: '是否中共党员' },
          { fieldName: 'ccp_congress_representative', comment: '中共党代表' },
          { fieldName: 'party_join_date', comment: '入党时间' },
          { fieldName: 'non_party_non_supervision', comment: '非党员非监察对象' },
          { fieldName: 'non_party_non_supervision_detail', comment: '非党员非监察对象详情' },
          { fieldName: 'npc_member', comment: '人大代表' },
          { fieldName: 'cppcc_member', comment: '政协委员' },
          { fieldName: 'is_discipline_inspection_official', comment: '是否纪检监察干部' },
          { fieldName: 'discipline_inspection_committee', comment: '纪委委员' },
          { fieldName: 'party_committee', comment: '党委委员' },
          { fieldName: 'current_position_start_date', comment: '任现职时间' },
          { fieldName: 'principal_violation', comment: '一把手违纪违法' },
          { fieldName: 'principal_detail1', comment: '一把手细节' },
          { fieldName: 'principal_detail2', comment: '一把手细节2' },
          { fieldName: 'principal_rank', comment: '正副职级' },
          { fieldName: 'department_category', comment: '部门分类' },
          { fieldName: 'department_category1', comment: '部门分类1' },
          { fieldName: 'enterprise_nature', comment: '企业性质' },
          { fieldName: 'enterprise_nature1', comment: '企业性质1' },
          { fieldName: 'enterprise_personnel_category', comment: '企业人员类别' },
          { fieldName: 'enterprise_position', comment: '企业岗位' },
                    { fieldName: 'impact_end_date', comment: '影响期限结束时间' },

          // 金额信息
          { fieldName: 'misconduct_amount', comment: '失职渎职金额' },
          { fieldName: 'total_violation_amount', comment: '违纪违法总金额（万元）' },
          // 立案信息
          { fieldName: 'filing_stat_time', comment: '立案统计时间' },
          { fieldName: 'filing_time', comment: '立案时间' },
          { fieldName: 'case_source', comment: '案件来源' },
          { fieldName: 'inspection_found_level2', comment: '巡视巡察中发现二级分类' },
          { fieldName: 'superior_assigned_level2', comment: '上级交办转办二级分类' },
          { fieldName: 'discipline_filing_agency', comment: '纪委立案机关' },
          { fieldName: 'discipline_filing_time', comment: '纪委立案时间' },
          { fieldName: 'discipline_filing_stat_time', comment: '纪委立案统计时间' },
          { fieldName: 'supervision_filing_agency', comment: '监委立案机关' },
          { fieldName: 'supervision_filing_time', comment: '监委立案时间' },
          { fieldName: 'supervision_filing_stat_time', comment: '监委立案统计时间' },
          { fieldName: 'is_transferred_after_filing', comment: '是否其他纪检监察机关立案后移送' },
          { fieldName: 'transfer_method', comment: '立案后移送方式' },
          { fieldName: 'transfer_unit', comment: '移送单位' },
          { fieldName: 'brief_case_description', comment: '简要案情' },
          { fieldName: 'filing_report', comment: '立案报告' },
          { fieldName: 'filing_decision', comment: '立案决定书' },
          { fieldName: 'remarks', comment: '备注' },
          // 特征信息
          { fieldName: 'is_violate_central_regulations', comment: '是否违反中央八项规定精神' },
          { fieldName: 'is_accountability_case', comment: '是否属于问责' },
          { fieldName: 'is_voluntary_confession', comment: '是否主动交代问题' },
          // 结案信息
          { fieldName: 'closing_stat_time', comment: '结案统计时间' },
          { fieldName: 'case_cancellation_time', comment: '销案时间' },
          { fieldName: 'closing_time', comment: '结案时间' },
          // 处分信息
          { fieldName: 'party_discipline_punishment', comment: '党纪处分' },
          { fieldName: 'is_should_dismiss_but_given_warning', comment: '是否本应撤销党内职务但给予严重警告' },
          { fieldName: 'party_punishment_stat_time', comment: '党纪处分统计时间' },
          { fieldName: 'administrative_punishment', comment: '政务处分' },
          { fieldName: 'admin_punishment_stat_time', comment: '政务处分统计时间' },
          { fieldName: 'other_treatment', comment: '其他处理' },
          { fieldName: 'other_treatment_stat_time', comment: '其他处理统计时间' },
          // 司法处理
          { fieldName: 'transfer_prosecution_time', comment: '移送检察机关时间' },
          { fieldName: 'transfer_prosecution_stat_time', comment: '移送检察机关统计时间' },
          { fieldName: 'criminal_punishment_main', comment: '刑事处理主刑' },
          { fieldName: 'criminal_punishment_additional', comment: '刑事处理附加刑' },
          { fieldName: 'main_sentence_years', comment: '主刑年数' },
          { fieldName: 'main_sentence_months', comment: '主刑月数' },
          { fieldName: 'probation_years', comment: '缓刑年数' },
          { fieldName: 'probation_months', comment: '缓刑月数' },
          { fieldName: 'court_judgment_stat_time', comment: '审判机关判决统计时间' },
          // 经济处理
          { fieldName: 'recover_economic_loss', comment: '挽回经济损失（万元）' },
          { fieldName: 'recovery_amount', comment: '收缴金额（万元）' },
          { fieldName: 'confiscation_amount', comment: '没收金额' },
          { fieldName: 'order_refund_amount', comment: '责令退赔金额' },
          { fieldName: 'register_submit_amount', comment: '登记上交金额' },
          { fieldName: 'recover_loss_due_to_misconduct', comment: '追缴失职渎职滥用职权造成的损失金额' },
          // 时间信息
          { fieldName: 'first_violation_time', comment: '首次违纪违法时间' },
          { fieldName: 'last_violation_time', comment: '末次违纪违法时间' },
          { fieldName: 'other_violation_time', comment: '其他违纪违法时间' },
          { fieldName: 'escape_time', comment: '潜逃时间' },
          { fieldName: 'escape_stat_time', comment: '潜逃统计时间' },
          // 审理信息
          { fieldName: 'trial_accept_time', comment: '审理受理时间' },
          { fieldName: 'trial_accept_stat_time', comment: '审理受理统计时间' },
          { fieldName: 'trial_agency', comment: '审理机关' },
          { fieldName: 'trial_completion_time', comment: '审结时间' },
          { fieldName: 'trial_completion_stat_time', comment: '审结统计时间' },
          { fieldName: 'punishment_decision', comment: '处分决定' },
          { fieldName: 'court_judgment_time', comment: '审判机关判决时间' },
          { fieldName: 'judicial_judgment_amount', comment: '司法判决金额（万元）' },
          // 报告文件
          { fieldName: 'investigation_report', comment: '审查调查报告' },
          { fieldName: 'trial_report', comment: '审理报告' },
          { fieldName: 'case_analysis', comment: '案件剖析' },
          // 其他处分信息
          { fieldName: 'probation_period_years', comment: '留党察看年限' },
          { fieldName: 'enterprise_level', comment: '企业级别' },
          { fieldName: 'escape_destination', comment: '潜逃去向' },
          { fieldName: 'escape_destination_detail', comment: '潜逃去向细节' },
          // 调查信息
          { fieldName: 'investigation_suspension_time', comment: '调查中止时间' },
          { fieldName: 'investigation_suspension_stat_time', comment: '调查中止统计时间' },
          { fieldName: 'capture_time', comment: '抓获时间' },
          { fieldName: 'capture_stat_time', comment: '抓获统计时间' },
          { fieldName: 'case_analysis_report_stat_time', comment: '案件剖析报告统计时间' },
          // 行为分类
          { fieldName: 'disciplinary_violation', comment: '违纪行为' },
          { fieldName: 'duty_illegal_crime', comment: '职务违法犯罪行为' },
          { fieldName: 'other_illegal_crime', comment: '其他违法犯罪行为' },
          // 措施信息
          { fieldName: 'measure_agency', comment: '采取措施机关' },
          { fieldName: 'measure_agency_name', comment: '采取措施机关名称' },
          { fieldName: 'detention_start_time', comment: '留置起始时间' },
          { fieldName: 'detention_start_stat_time', comment: '留置起始统计时间' },
          { fieldName: 'measure_location', comment: '采取措施地点' },
          { fieldName: 'measure_location_category', comment: '采取措施地点分类' },
          { fieldName: 'detention_decision', comment: '留置决定书' },
          { fieldName: 'detention_end_time', comment: '留置结束时间' },
          { fieldName: 'detention_end_stat_time', comment: '留置结束统计时间' },
          { fieldName: 'detention_days', comment: '留置天数' },
          { fieldName: 'is_extension', comment: '是否延期' },
          { fieldName: 'extension_days', comment: '延期天数' },
          { fieldName: 'extended_detention_decision', comment: '延长留置时间决定书' },
          // 特征分类
          { fieldName: 'is_masses_problem', comment: '是否群众身边的不正之风和腐败问题' },
          // 组织措施
          { fieldName: 'organizational_measures', comment: '组织措施' },
          { fieldName: 'organizational_measures_stat_time', comment: '组织措施统计时间' },
          // 其他金额
          { fieldName: 'transfer_prosecution_amount', comment: '移送检察机关金额（万元）' },
          // 历史措施
          { fieldName: 'shuanggui_start_time', comment: '两规两指起始时间' },
          { fieldName: 'shuanggui_stat_time', comment: '两规两指统计时间' },
          { fieldName: 'shuanggui_end_time', comment: '两规两指解除时间' },
          { fieldName: 'shuanggui_end_stat_time', comment: '两规两指解除统计时间' },
          // 忏悔材料
          { fieldName: 'confession', comment: '忏悔书' },
          // 投案信息
          { fieldName: 'is_voluntary_surrender', comment: '是否主动投案' },
          { fieldName: 'is_report_to_superior', comment: '是否属于向上级纪委监委报告范围' },
          // 补充调查
          { fieldName: 'is_return_supplementary_investigation', comment: '是否退回补充调查' },
          { fieldName: 'return_supplementary_time', comment: '退回补充调查时间' },
          { fieldName: 'return_supplementary_stat_time', comment: '退回补充调查统计时间' },
          { fieldName: 'return_supplementary_reason', comment: '退回补充调查原因' },
          { fieldName: 'is_second_return_supplementary', comment: '是否二次退回补充调查' },
          { fieldName: 'second_return_supplementary_time', comment: '二次退回补充调查时间' },
          { fieldName: 'second_return_supplementary_stat_time', comment: '二次退回补充调查统计时间' },
          { fieldName: 'second_return_supplementary_reason', comment: '二次退回补充调查原因' },
          // 不起诉信息
          { fieldName: 'is_no_prosecution', comment: '是否不起诉' },
          { fieldName: 'no_prosecution_reason', comment: '不起诉原因' },
          { fieldName: 'no_prosecution_decision_time', comment: '决定不起诉时间' },
          { fieldName: 'no_prosecution_decision_stat_time', comment: '决定不起诉统计时间' },
          // 司法信息
          { fieldName: 'court_judgment_crime', comment: '审判机关判决罪名' },
          { fieldName: 'public_security_punishment', comment: '公安等其他行政法机关处罚' },
          { fieldName: 'public_security_punishment_detail', comment: '公安等其他行政法机关处罚详细内容' },
          { fieldName: 'transfer_public_security_time', comment: '移送公安机关时间' },
          { fieldName: 'transfer_public_security_stat_time', comment: '移送公安机关统计时间' },
          { fieldName: 'public_security_punishment_time', comment: '公安等其他行政法机关处罚时间' },
          { fieldName: 'public_security_punishment_stat_time', comment: '公安等其他行政法机关处罚统计时间' },
          // 处分变更
          { fieldName: 'change_punishment_time', comment: '变更处分时间' },
          { fieldName: 'revoke_punishment_time', comment: '撤销处分时间' },
          { fieldName: 'change_punishment_stat_time', comment: '变更处分统计时间' },
          { fieldName: 'revoke_punishment_stat_time', comment: '撤销处分统计时间' },
          { fieldName: 'change_revoke_reason', comment: '变更撤销原因' },
          { fieldName: 'new_party_punishment', comment: '新党纪处分' },
          { fieldName: 'is_new_should_dismiss_but_warning', comment: '新党纪处分是否属于"本应撤销党内职务但给予严重警告"' },
          { fieldName: 'new_probation_period_years', comment: '新留党察看年限' },
          { fieldName: 'new_administrative_punishment', comment: '新政务处分' },
          { fieldName: 'new_other_treatment', comment: '新其他处理' },
          { fieldName: 'new_organizational_measures', comment: '新组织措施' },
          // 从宽处罚建议
          { fieldName: 'is_leniency_suggestion', comment: '监察机关是否提出从宽处罚建议' },
          { fieldName: 'leniency_suggestion_type', comment: '从宽处罚建议类型' },
          { fieldName: 'leniency_suggestion_situation', comment: '监察机关提出从宽处罚建议的情形' },
          { fieldName: 'leniency_suggestion_stat_time', comment: '提出从宽处罚建议统计时间' },
          { fieldName: 'is_prosecution_adopt_leniency', comment: '检察机关是否采纳从宽处罚建议' },
          { fieldName: 'prosecution_adopt_leniency_time', comment: '检察机关采纳从宽处罚建议时间' },
          { fieldName: 'prosecution_adopt_leniency_stat_time', comment: '检察机关采纳从宽处罚建议统计时间' },
          { fieldName: 'is_court_adopt_leniency', comment: '审判机关是否采纳从宽处罚建议' },
          { fieldName: 'court_adopt_leniency_time', comment: '审判机关采纳从宽处罚建议时间' },
          { fieldName: 'court_adopt_leniency_stat_time', comment: '审判机关采纳从宽处罚建议统计时间' },
          // 法律文书
          { fieldName: 'prosecution_transfer_opinion', comment: '纪检监察机关移送检察机关起诉意见书' },
          // 调查措施使用次数
          { fieldName: 'freeze_measure_count', comment: '冻结措施使用次数' },
          { fieldName: 'search_measure_count', comment: '搜查措施使用次数' },
          { fieldName: 'seizure_measure_count', comment: '查封使用次数' },
          { fieldName: 'control_measure_count', comment: '扣押使用次数' },
          { fieldName: 'tech_investigation_count', comment: '技术调查使用次数' },
          { fieldName: 'wanted_count', comment: '通缉使用次数' },
          { fieldName: 'exit_restriction_count', comment: '限制出境使用次数' },
          // 措施使用情况
          { fieldName: 'freeze_measure_situation', comment: '冻结措施使用情况' },
          { fieldName: 'search_measure_situation', comment: '搜查措施使用情况' },
          { fieldName: 'seizure_measure_situation', comment: '查封措施使用情况' },
          { fieldName: 'control_measure_situation', comment: '扣押措施使用情况' },
          { fieldName: 'tech_investigation_situation', comment: '技术调查措施使用情况' },
          { fieldName: 'wanted_measure_situation', comment: '通缉措施使用情况' },
          { fieldName: 'exit_restriction_situation', comment: '限制出境措施使用情况' },
          // 统计时间
          { fieldName: 'measure_usage_stat_time', comment: '使用措施统计时间' },
          { fieldName: 'remarks_stat_time', comment: '备注统计时间' },
          // 纪检监察建议（8条）
          { fieldName: 'suggesting_agency1', comment: '提出建议的纪检监察机构名称1' },
          { fieldName: 'suggested_unit1', comment: '被建议的单位（组织）名称1' },
          { fieldName: 'suggestion_type1', comment: '建议类型1' },
          { fieldName: 'suggestion_content1', comment: '建议文书内容1' },
          { fieldName: 'suggestion_time1', comment: '提出建议时间1' },
          { fieldName: 'suggestion_stat_time1', comment: '提出建议统计时间1' },
          { fieldName: 'suggesting_agency2', comment: '提出建议的纪检监察机构名称2' },
          { fieldName: 'suggested_unit2', comment: '被建议的单位（组织）名称2' },
          { fieldName: 'suggestion_type2', comment: '建议类型2' },
          { fieldName: 'suggestion_content2', comment: '建议文书内容2' },
          { fieldName: 'suggestion_time2', comment: '提出建议时间2' },
          { fieldName: 'suggestion_stat_time2', comment: '提出建议统计时间2' },
          { fieldName: 'suggesting_agency3', comment: '提出建议的纪检监察机构名称3' },
          { fieldName: 'suggested_unit3', comment: '被建议的单位（组织）名称3' },
          { fieldName: 'suggestion_type3', comment: '建议类型3' },
          { fieldName: 'suggestion_content3', comment: '建议文书内容3' },
          { fieldName: 'suggestion_time3', comment: '提出建议时间3' },
          { fieldName: 'suggestion_stat_time3', comment: '提出建议统计时间3' },
          { fieldName: 'suggesting_agency4', comment: '提出建议的纪检监察机构名称4' },
          { fieldName: 'suggested_unit4', comment: '被建议的单位（组织）名称4' },
          { fieldName: 'suggestion_type4', comment: '建议类型4' },
          { fieldName: 'suggestion_content4', comment: '建议文书内容4' },
          { fieldName: 'suggestion_time4', comment: '提出建议时间4' },
          { fieldName: 'suggestion_stat_time4', comment: '提出建议统计时间4' },
          { fieldName: 'suggesting_agency5', comment: '提出建议的纪检监察机构名称5' },
          { fieldName: 'suggested_unit5', comment: '被建议的单位（组织）名称5' },
          { fieldName: 'suggestion_type5', comment: '建议类型5' },
          { fieldName: 'suggestion_content5', comment: '建议文书内容5' },
          { fieldName: 'suggestion_time5', comment: '提出建议时间5' },
          { fieldName: 'suggestion_stat_time5', comment: '提出建议统计时间5' },
          { fieldName: 'suggesting_agency6', comment: '提出建议的纪检监察机构名称6' },
          { fieldName: 'suggested_unit6', comment: '被建议的单位（组织）名称6' },
          { fieldName: 'suggestion_type6', comment: '建议类型6' },
          { fieldName: 'suggestion_content6', comment: '建议文书内容6' },
          { fieldName: 'suggestion_time6', comment: '提出建议时间6' },
          { fieldName: 'suggestion_stat_time6', comment: '提出建议统计时间6' },
          { fieldName: 'suggesting_agency7', comment: '提出建议的纪检监察机构名称7' },
          { fieldName: 'suggested_unit7', comment: '被建议的单位（组织）名称7' },
          { fieldName: 'suggestion_type7', comment: '建议类型7' },
          { fieldName: 'suggestion_content7', comment: '建议文书内容7' },
          { fieldName: 'suggestion_time7', comment: '提出建议时间7' },
          { fieldName: 'suggestion_stat_time7', comment: '提出建议统计时间7' },
          { fieldName: 'suggesting_agency8', comment: '提出建议的纪检监察机构名称8' },
          { fieldName: 'suggested_unit8', comment: '被建议的单位（组织）名称8' },
          { fieldName: 'suggestion_type8', comment: '建议类型8' },
          { fieldName: 'suggestion_content8', comment: '建议文书内容8' },
          { fieldName: 'suggestion_time8', comment: '提出建议时间8' },
          { fieldName: 'suggestion_stat_time8', comment: '提出建议统计时间8' },
          // 涉外信息
          { fieldName: 'foreign_related_category', comment: '涉外类别' },
          { fieldName: 'involved_country', comment: '涉及国家（地区）' },
          { fieldName: 'foreign_related_stat_time', comment: '涉外统计时间' },
          { fieldName: 'foreign_related_summary', comment: '涉外信息摘要' },
          // 其他信息
          { fieldName: 'unrecovered_overseas_assets', comment: '尚未追回的境外涉案财物' },
          { fieldName: 'is_self_handled_case', comment: '纪检监察机关自办案件' },
          { fieldName: 'is_public_security_transferred_case', comment: '公检法等机关移送的非职务违法犯罪等案件' },
          { fieldName: 'public_security_transferred_detail', comment: '公检法等机关移送的非职务违法犯罪等案件二级分类' },
          { fieldName: 'detention_object_identity', comment: '留置对象身份' },
          { fieldName: 'corruption_bribery_time', comment: '贪污贿赂行为发生时间' },
          { fieldName: 'corruption_bribery_first_year', comment: '贪污贿赂行为的首次年份' },
          
          { fieldName: 'duty_ethics_reply_time', comment: '党风廉政意见回复时间' },
{ fieldName: 'duty_ethics_reply_type', comment: '党风廉政意见回复类型' },
{ fieldName: 'duty_ethics_reply_person_count', comment: '党风廉政意见回复涉及人次' },
{ fieldName: 'duty_ethics_reply_materials', comment: '党风廉政意见回复材料' },

{ fieldName: 'false_report_handle_time', comment: '不如实报告处理时间' },
{ fieldName: 'false_report_issue', comment: '不如实报告问题' },
{ fieldName: 'false_report_disposal', comment: '不如实报告处理情况' },
{ fieldName: 'false_report_punishment_no', comment: '不如实报告处分文号' },
{ fieldName: 'false_report_remarks', comment: '不如实报告备注' },

{ fieldName: 'other_integrity_material_time', comment: '其他廉政材料时间' },
{ fieldName: 'other_integrity_material_name', comment: '其他廉政材料名称' },
{ fieldName: 'other_integrity_material_content', comment: '其他廉政材料内容' },
{ fieldName: 'other_integrity_material_department', comment: '其他廉政材料形成部门' },
{ fieldName: 'other_integrity_material_remarks', comment: '其他廉政材料备注' },
          // 系统字段
          // { fieldName: 'created_at', comment: '创建时间' },
          // { fieldName: 'updated_at', comment: '更新时间' }
        ],
        'personal_matters_report_punishment': [
          // { fieldName: 'id', comment: 'ID' },
          // 基本信息
          { fieldName: 'time_period', comment: '时间' },
          { fieldName: 'problem_description', comment: '问题' },
          { fieldName: 'handling_situation', comment: '处理情况' },
          { fieldName: 'punishment_document_number', comment: '处分文号' },
          { fieldName: 'remarks', comment: '备注' },
          // 系统字段
          // { fieldName: 'created_at', comment: '创建时间' },
          // { fieldName: 'updated_at', comment: '更新时间' }
        ],
        'party_conduct_opinion_reply': [
          // { fieldName: 'id', comment: 'ID' },
          // 基本信息
          { fieldName: 'time_period', comment: '时间' },
          { fieldName: 'type', comment: '类型' },
          { fieldName: 'person_count', comment: '人次' },
          { fieldName: 'reply_document', comment: '回复材料' },
          // 系统字段
          // { fieldName: 'created_at', comment: '创建时间' },
          // { fieldName: 'updated_at', comment: '更新时间' }
        ],
        'other_clean_government_materials': [
          // { fieldName: 'id', comment: 'ID' },
          // 基本信息
          { fieldName: 'time_period', comment: '时间' },
          { fieldName: 'material_name', comment: '材料名称' },
          { fieldName: 'material_content', comment: '材料内容' },
          { fieldName: 'material_forming_department', comment: '材料形成部门' },
          { fieldName: 'remarks', comment: '备注' },
          // 系统字段
          // { fieldName: 'created_at', comment: '创建时间' },
          // { fieldName: 'updated_at', comment: '更新时间' }
        ]
      };

const emit = defineEmits(['confirm', 'close'])

// 模态框显示控制
const visible = ref(true)

// 单位选项（从数据库获取）
const unitOptions = ref([])

// 表选项（实际项目中应该从后端获取）
const tableOptions = ref([
  // { key: 'users', label: '用户表' },
  // { key: 'cases', label: '案件表' },
  { key: 'subUnits', label: '下属单位信息表' },
  { key: 'leader_personnel_infro', label: '领导人员个人基本信息表' },
  { key: 'new_leader_report', label: '新提拔领导人员个人有关事项报告表' },
  { key: 'problem_clues_situation', label: '问题线索表' },
  { key: 'discipline_organization_punishment', label: '受党纪处分和组织处理情况表' },
  { key: 'personal_matters_report_punishment', label: '不如实报告个人有关事项受处理情况表' },
  { key: 'party_conduct_opinion_reply', label: '党风廉政意见回复情况表' },
  { key: 'other_clean_government_materials', label: '其他反映廉政情况的材料表' }
])

// 获取已选择的表名集合
const getSelectedTableNames = () => {
  return props.form.viewableTables.map(table => table.key).filter(key => key);
}

// 检查表名是否已被选中
const isTableSelected = (tableName, currentRow) => {
  // 获取所有已选的表名（不包括当前行）
  const selectedTableNames = props.form.viewableTables
    .filter(table => table !== currentRow)
    .map(table => table.key)
    .filter(key => key);
  
  // 如果当前表名在已选列表中，则返回true（禁用）
  return selectedTableNames.includes(tableName);
}

// 从数据库获取启用状态的单位
const loadUnits = async () => {
  try {
    const units = await database.query('SELECT id, code, name FROM subUnits WHERE status = ?', ['启用'])
    unitOptions.value = units.map(unit => ({
      value: unit.code,
      label: `${unit.name} `,  // 显示名称和编码
      code: unit.code
    }))
  } catch (error) {
    console.error('Failed to load units:', error)
    unitOptions.value = []
  }
}

// 组件初始化时加载单位数据
onMounted(() => {
  loadUnits()
})
// 表名映射（用于显示）
const tableDisplayNameMap = {
  'cases': '案件表',
  'leader_personnel_infro': '领导人员信息表'
}

// 全选所有单位
const selectAllUnits = () => {
  // 获取所有单位的value
  const allUnitValues = unitOptions.value.map(unit => unit.value)
  
  // 设置到form.viewableUnits
  props.form.viewableUnits = allUnitValues
  
  // 显示提示信息
  ElMessage.success(`已全选 ${allUnitValues.length} 个单位`)
}

// 全选/取消选择列名
const selectAndDeselectAllColumns = (row, isSelectAll) => {
  if (isSelectAll) {
    // 全选当前行的所有列
    row.selectedColumns = row.columns.map(column => column.fieldName)
    ElMessage.success(`已全选 ${row.columns.length} 个列名`)
  } else {
    // 取消选择所有列
    row.selectedColumns = []
    ElMessage.info('已取消所有列名选择')
  }
}

// 确认保存
const confirm = async () => {
  try {
    // 验证表单数据
    if (!props.form.groupName.trim()) {
      throw new Error('分组名不能为空')
    }
    if (props.form.viewableUnits.length === 0) {
      throw new Error('请选择至少一个可查看单位')
    }
    if (props.form.viewableTables.length === 0) {
      throw new Error('请添加至少一个可查看表')
    }

    // 将单位id转换为单位code
    const unitCodes = props.form.viewableUnits.map(unitId => {
      const unit = unitOptions.value.find(u => u.value === unitId)
      return unit ? unit.code : ''
    }).filter(code => code) // 过滤掉空值
    
    // 准备export表数据
    const exportData = {
      export_name: props.form.groupName,
      units: unitCodes.join(',')
    }
    
    // 准备export_subtable表数据
    const subtableData = props.form.viewableTables.map(table => {
      return {
        table_name: table.name,
        columns: table.selectedColumns.join(',')
      }
    })
    
    if (props.isEdit) {
      // 编辑模式：更新现有记录
      const exportId = props.form.id;
      
      // 更新export表
      await database.update(
        'UPDATE export SET export_name = ?, units = ? WHERE export_id = ?',
        [exportData.export_name, exportData.units, exportId]
      )
      
      // 先删除现有export_subtable表数据
      await database.delete(
        'DELETE FROM export_subtable WHERE export_id = ?',
        [exportId]
      )
      
      // 插入新的export_subtable表数据
      for (const sub of subtableData) {
        await database.insert(
          'INSERT INTO export_subtable (export_id, table_name, columns) VALUES (?, ?, ?)',
          [exportId, sub.table_name, sub.columns]
        )
      }
      
      ElMessage.success('修改成功')
    } else {
      // 新增模式：创建新记录
      // 生成export_id
      const exportId = Date.now().toString() + Math.floor(Math.random() * 1000)
      
      // 更新exportData
      exportData.export_id = exportId
      
      // 插入export表
      await database.insert(
        'INSERT INTO export (export_id, export_name, units) VALUES (?, ?, ?)',
        [exportData.export_id, exportData.export_name, exportData.units]
      )
      
      // 插入export_subtable表数据
      for (const sub of subtableData) {
        await database.insert(
          'INSERT INTO export_subtable (export_id, table_name, columns) VALUES (?, ?, ?)',
          [exportId, sub.table_name, sub.columns]
        )
      }
      
      ElMessage.success('保存成功')
    }
    
    visible.value = false
    emit('get-list')
    emit('close')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error(`保存失败: ${error.message}`)
  }
}

// 表选择变化事件
const handleTableChange = (row, tableKey) => {
  if (tableKey && tableColumns[tableKey]) {
    // 直接更新row对象
    row.columns = [...tableColumns[tableKey]]
    row.name = tableKey // 更新name为正确的key
  } else {
    row.columns = []
    row.name = ''
  }
}

// 新增行
const handleAddRow = () => {
  try {
    // 多层安全检查
    if (!props.form) {
      throw new Error('Form对象未定义');
    }
    
    // 确保viewableTables是一个数组
    if (!Array.isArray(props.form.viewableTables)) {
      props.form.viewableTables = [];
    }
    
    // 添加新行
    props.form.viewableTables.push({
      name: '',
      columns: [],
      selectedColumns: [],
      key: ''
    });
  } catch (error) {
    console.error('新增行失败:', error);
    ElMessage.error('新增行失败: ' + error.message);
  }
}

// 删除行
const handleDeleteRow = (row) => {
  const index = props.form.viewableTables.indexOf(row)
  if (index !== -1) {
    props.form.viewableTables.splice(index, 1)
  }
}

// 监听visible变化，关闭时重置状态
watch(visible, (val) => {
  if (!val) {
    // 可以在这里添加重置逻辑
  }
})
</script>
    <style scoped>
    /* 图标加粗样式 */
    :deep(.el-icon) {
      font-weight: bold;
    }
    
    /* 为按钮中的图标特别设置加粗 */
    :deep(.el-button .el-icon) {
      font-weight: 700;
    }
    
    /* 单独设置删除按钮的图标加粗 */
    :deep(.el-button--danger .el-icon) {
      font-weight: 900;
    }
    
    /* 表格操作按钮样式 */
    .table-actions {
      display: flex;
      gap: 8px;
    }
    </style>